<?php

namespace app\admin\controller\business;

use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\Business\Business;
use app\common\model\Business\Receive;
use Exception;
use think\Db;
use think\exception\PDOException;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Highsea extends Backend
{

    /**
     * Highsea模型对象
     * @var \app\admin\model\business\Highsea
     */
    protected $model = null;
    protected $receiveModel = null;
    protected $adminModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Business();
        $this->receiveModel = new Receive();
        $this->adminModel = new Admin();
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("dealList", $this->model->getDealList());
        $this->view->assign("authList", $this->model->getAuthList());

        $this->assignconfig("sourceList", $this->model->getSourceList());
        $this->modelValidate = true;
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $this->relationSearch = true;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     public function index()
     {
         //设置过滤方法
         $this->request->filter(['strip_tags', 'trim']);
         if (false === $this->request->isAjax()) {
             return $this->view->fetch();
         }
         //如果发送的来源是 Selectpage，则转发到 Selectpage
         if ($this->request->request('keyField')) {
             return $this->selectpage();
         }
 
         $filter = json_decode($this->request->get('filter'),true);
         $op = json_decode($this->request->get('op'),true);
         if (isset($filter['source.name'])){
             $cost_where['source.name'] = $filter['source.name'];
             $filter['source.id'] = $filter['source.name'];
             $op['source.id'] = $op['source.name'];
             unset($filter['source.name']);
             unset($op['source.name']);
         }
         $this->request->get(['filter'=>json_encode($filter)]);
         $this->request->get(['op'=>json_encode($op)]);
 
         [$where, $sort, $order, $offset, $limit] = $this->buildparams();
         // halt($where);
         $whereHighsea = ['adminid'=>null];
         $list = $this->model
             ->with(['source'])
             ->where($where)
             ->where($whereHighsea)
             ->order($sort, $order)
             ->paginate($limit);
         $result = ['total' => $list->total(), 'rows' => $list->items()];
         return json($result);
     }
     public function apply($ids,$status='',$adminid=0)
     {
        if(!$status)
        {
            $status = 'apply';
        }
        $rows = $this->model->where('id','in',$ids)->select();
        if (!$rows->count()) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($rows->get(0)[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $adminid = $adminid?$adminid:$this->auth->id;
        $dataBusiness = [];
        $dataReceive = [];
        foreach($rows as $row)
        {
            $dataBusiness[] = [
                'id'=>$row['id'],
                'adminid'=>$adminid,
            ];
            $dataReceive[] = [
                'applyid'=>$adminid,
                'status'=>$status,
                'busid'=>$row['id']
            ];
        }
        
        $result = false;
        Db::startTrans();
        try {
            $this->model->isUpdate(true)->saveAll($dataBusiness);
            // $result = Receive::create($data);
            $result = $this->receiveModel->saveAll($dataReceive);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
     }
     public function allot($ids)
     {
        if (false === $this->request->isAjax()) {
            $childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
            $admins = $this->adminModel->where('id','in',$childrenAdminIds)->column('id,nickname');
            $adminlist = build_select('row[adminid]',$admins,[],['class'=>'selectpicker', 'required'=>'']);
            $this->assign('adminlist',$adminlist);
            return $this->view->fetch();
        }
        if($this->request->isGet()){
            $total = $this->model->where('id','in',$ids)->count();
            $rows = $this->model->where('id','in',$ids)->select()->toArray();
            $result = ['total' => $total, 'rows' => $rows];
            $this->assign('adminlist',$result);
            return json($result);
        }
        $adminid = $this->request->post('row/a')['adminid'];
        $this->apply($ids,'allot',$adminid);
     }
}
